<script setup>
import {onMounted, ref} from "vue";
import {AddEmbeddings, DeleteAllFiles, DeleteOneFile, GenerateGraph, ListFiles} from "@/api/graphFileApi.js";
import {ElButton, ElInput, ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {userTokenStore} from "@/store/userTokenStore.js";
import {userInfoStore} from "@/store/userInfoStore.js";
import {Delete, DocumentAdd, Refresh, Search, Upload} from "@element-plus/icons-vue";

const files = ref([]); // 文件列表
const selectedFile = ref(""); // 当前选中的文件名
const TokenStore = userTokenStore();
const userInfo = userInfoStore();
const RAGFILEPATH = "D:\\python\\pythonprojects\\flask\\graphrag\\public\\file\\"
const RAGEMBEDDINGPATH = "D:\\python\\pythonprojects\\flask\\graphrag\\public\\embeddings\\"
const RAGGRAPHPATH = "D:\\python\\pythonprojects\\flask\\graphrag\\public\\graph\\"

const current = ref(1) //当前页
const pageSize = ref(10) //每页条数
const total = ref(20) //总条数
//分页条数据模型
const form = ref({
  id: null, //id
  file_name: '', //文件名称
  isIndex: null,//是否建立索引
  create_time: null, // 用户角色
  isDelete: null,
  sortField: '',//排序字段
  sortOrder: ''//排序顺序
})

// 排序字段
const fields = ref(
    {
      "ID":"id",
      "文件名称":"file_name",
      "创建时间":"create_time",
    }
)

const getFileList = async () => {
  const params = {
    id: (form.value.id!=null&&form.value.id>0)?form.value.id:null,
    file_name: form.value.file_name===""?null:form.value.file_name,
    isIndex: form.value.isIndex==null||form.value.isIndex<=0?null:form.value.isIndex,//
    isDelete: form.value.isDelete==null||form.value.isDelete<=0?null:form.value.isDelete,//
    create_time: form.value.create_time==null?null:form.value.create_time,//
    sortField: form.value.sortField===""?null:form.value.sortField,//排序字段
    sortOrder: form.value.sortOrder===""?null:form.value.sortOrder,//排序顺序
    current: current.value,
    pageSize: pageSize.value
  }
  console.log("params: ", params);
  const answer = await ListFiles(params);
  console.log("file data: ", answer);
  files.value = answer.data.file_result;
  total.value = answer.data.total;
}

const clearForm = ()=>{
  form.value={
    id: null, //id
    file_name: '', //文件名称
    isIndex: null,//是否建立索引
    create_time: null, // 用户角色
    isDelete: null,
    sortField: '',//排序字段
    sortOrder: ''//排序顺序
  }
}
onMounted(async () => {
  try {
    await getFileList();
    console.log("Files loaded:", files.value);
  } catch (error) {
    console.error("Error loading files:", error);
  }
});

// 选择当前文件
const selectFile = (fileName) => {
  selectedFile.value = fileName;
};



const handleUploadSuccess = (response, file, fileList) => {
  const data= response.data;
  console.log(data);
  // 上传成功后的回调
  ElMessage.success('文件上传成功');
  getFileList();
};

const deleteOneFile = async (file) => {
  ElMessageBox.confirm('确定要删除该文件吗?该操作不影响已经建立的索引', '提示', {    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    console.log("file",file);
    await DeleteOneFile(file);
    ElMessage.success('删除成功');
    await getFileList();
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

const deleteAllFile = async () => {
  ElMessageBox.confirm('确定要删除所有文件吗？这会导致所有索引也会被删除?', '提示', {    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await DeleteAllFiles();
    ElMessage.success('删除成功');
    await getFileList();
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

const generateEmbeddings = async (file) => {
  ElMessageBox.confirm(`确定要为 ${selectedFile.value} 建立索引吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 显示加载遮罩
    const loading = ElLoading.service({
      lock: true,
      text: '正在建立索引，请稍候...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
      await AddEmbeddings(file);
      ElMessage.success('索引建立成功');
      await getFileList();
    } catch (error) {
      ElMessage.error('索引建立失败');
    } finally {
      // 关闭加载遮罩
      loading.close();
    }
  }).catch(() => {
    ElMessage.info('已取消建立索引');
  })
}

const generateGraph = async (file) => {
  ElMessageBox.confirm(`确定要为 ${selectedFile.value} 建立关系图吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 显示加载遮罩
    const loading = ElLoading.service({
      lock: true,
      text: '正在建立关系图，请稍候...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    try {
      await GenerateGraph(file);
      ElMessage.success('地图建立成功，请前往知识地图部分查看');
      await getFileList();
    } catch (error) {
      ElMessage.error('地图建立失败');
    } finally {
      // 关闭加载遮罩
      loading.close();
    }
}).catch(()=>{
    ElMessage.info('已取消建立地图');
  })
}

//当每页条数发生了变化，调用此函数
const onSizeChange = async (size) => {
  pageSize.value = size;
  await getFileList();
};
//当前页码发生变化，调用此函数
const onCurrentChange = async (num) => {
  current.value = num;
  await getFileList()
};
</script>

<template>
  <div class="file-management-container">
    <el-card class="file-management-card">
      <div class="header-section">
        <h2 class="section-title">我的知识库</h2>
        <div class="action-buttons">
          <el-text type="info" class="selected-file">当前选中: {{ selectedFile || '无' }}</el-text>

          <el-upload
              class="upload-button"
              action="/api/ai/file/upload"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              name="file"
              :auto-upload="true"
              :headers="{'Authorization':TokenStore.token}"
          >
            <el-button type="primary" :icon="Upload" plain>上传文件</el-button>
          </el-upload>

          <el-button
              type="success"
              :icon="DocumentAdd"
              plain
              @click="generateEmbeddings({file_path:RAGFILEPATH+userInfo.info.id+'\\'+selectedFile})"
              :disabled="!selectedFile"
          >
            构建索引
          </el-button>

          <el-button
              type="warning"
              :icon="Delete"
              plain
              @click="generateGraph({file_path:RAGFILEPATH+userInfo.info.id+'\\'+selectedFile})"
              :disabled="!selectedFile"
          >
            构建地图
          </el-button>

          <el-button
              type="danger"
              :icon="Delete"
              plain
              @click="deleteAllFile"
          >
            清空所有
          </el-button>
        </div>
      </div>

      <el-divider class="custom-divider" />

      <div class="search-form">
        <el-form :model="form" inline class="advanced-search-form" @keyup.enter="getFileList">
          <el-form-item label="文件ID" prop="id">
            <el-input
                v-model="form.id"
                placeholder="请输入文件ID"
                clearable
                class="search-input"
            />
          </el-form-item>

          <el-form-item label="文件名" prop="file_name">
            <el-input
                v-model="form.file_name"
                placeholder="请输入文件名"
                clearable
                class="search-input"
            />
          </el-form-item>

          <el-form-item label="索引状态" prop="isIndex">
            <el-select
                v-model="form.isIndex"
                placeholder="请选择"
                clearable
                class="search-select"
            >
              <el-option label="所有" value="-1" />
              <el-option label="未建立" value="0" />
              <el-option label="已建立" value="1" />
            </el-select>
          </el-form-item>

          <el-form-item label="排序字段" prop="sortField">
            <el-select
                v-model="form.sortField"
                placeholder="请选择"
                clearable
                class="search-select"
            >
              <el-option
                  v-for="([label, value]) in Object.entries(fields)"
                  :key="value"
                  :label="label"
                  :value="value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="排序方式" prop="sortOrder">
            <el-select
                v-model="form.sortOrder"
                placeholder="请选择"
                clearable
                class="search-select"
            >
              <el-option label="升序" value="asc" />
              <el-option label="降序" value="desc" />
            </el-select>
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button type="primary" :icon="Search" @click="getFileList">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-divider class="custom-divider" />

      <div class="table-section">
        <el-table
            :data="files"
            style="width: 100%"
            v-if="files.length > 0"
            stripe
            highlight-current-row
            :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="ID" prop="id" width="80" align="center" />
          <el-table-column label="文件名称" prop="file_name" min-width="180" />
          <el-table-column label="索引状态" prop="isIndex" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isIndex === 1 ? 'success' : 'info'" effect="plain">
                {{ row.isIndex === 1 ? '已建立' : '未建立' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="create_time" width="180" align="center" />
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="deleteOneFile({file_name:row.file_name})"
                  plain
              >
                删除
              </el-button>
              <el-button
                  type="primary"
                  size="small"
                  :icon="Select"
                  @click="selectFile(row.file_name)"
                  plain
              >
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-else description="暂无文件数据" />
      </div>

      <div class="pagination-section">
        <el-pagination
            v-model:current-page="current"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :background="true"
            :total="total"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.file-management-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.file-management-card {
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.06);
  border: none;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-title {
  font-size: 22px;
  color: #303133;
  font-weight: 600;
  margin: 0;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selected-file {
  font-size: 14px;
  color: #909399;
  margin-right: 15px;
}

.custom-divider {
  margin: 12px 0;
  border-color: #e4e7ed;
}

.search-form {
  padding: 15px 0;
}

.advanced-search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 150px;
}

.form-actions {
  margin-left: auto;
}

.table-section {
  margin: 20px 0;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 按钮科技感增强 */
:deep(el-button) {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

:deep(el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(el-button:active) {
  transform: translateY(0);
}

:deep(el-button.is-plain:hover) {
  background-color: rgba(64, 158, 255, 0.1);
}

:deep(el-table) {
  font-size: 14px;
}

:deep(.el-table__header th) {
  font-weight: 600;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: #fff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled):hover) {
  color: #409eff;
}
</style>